package com.tinem.platform.module.starter;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.vo.error.SystemException;
import com.tinem.platform.module.starter.config.EmqxConfiguration;
import com.tinem.platform.module.starter.sdk.MessageCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className EmqxClient
 * @description TODO
 * @site
 * @company
 * @create 2022/1/19 15:18:22
 */
@Slf4j
public class EmqxClient {

    Map<String, EmqxConfiguration.Config> config;
    public EmqxClient( List<EmqxConfiguration.Config> config){
        this.config = config.stream().collect(Collectors.toMap(EmqxConfiguration.Config::getClientId, Function.identity()));
    }

    /**
     * 获取用户在线状态
     * @return
     */
    public boolean getOnlineStatus(String clientId, String topic){
        EmqxConfiguration.Config config = this.config.get(clientId);
        if(config == null){
            log.error("client config not find:{}",clientId);
            throw new SystemException(MessageCode.ERROR_COMMONS_UNKNOWN);
        }

        String url = config.getUrl()+"/api/v4/subscriptions?_page=1&_limit=10&topic="+topic;
        log.info("post url:{}",url);
        String res = HttpRequest.get(url)
                .basicAuth(config.getUserName(),config.getPassword())
                .execute().body();
        log.info("post res:{}",res);
        JSONObject body = JSON.parseObject(res);
        if(body.getInteger("code") != 0){
            return false;
        }
        return body.getJSONArray("data").size()>0;
    }

    public boolean sendMessageTopics(String clientId, String topics, String payLoad){
        return sendMessage(clientId,null,topics,payLoad);

    }
    public boolean sendMessageTopic(String clientId, String topic, String payLoad){
        return sendMessage(clientId,topic,null,payLoad);
    }
    /**
     * 发送消息
     * @param clientId
     * @param topic
     * @param payLoad
     * @return
     */
    public boolean sendMessage(String clientId, String topic, String topics, String payLoad){
        EmqxConfiguration.Config config = this.config.get(clientId);
        if(config == null){
            throw new SystemException(MessageCode.ERROR_COMMONS_UNKNOWN);
        }

        JSONObject params = new JSONObject(){{
            put("topic",topic);
            put("topics",topics);
            put("clientid","http");
            put("payload",payLoad);
            put("encoding","plain");
            put("qos",2);
            put("retain",false);
        }};
        String url = config.getUrl()+"/api/v4/mqtt/publish";
        log.info("post url:{}",url);
        if(log.isDebugEnabled()){
            log.debug("post params:{}",params.toJSONString());
        }
        String res = HttpRequest.post(url)
                .body(params.toJSONString(),"application/json")
                .basicAuth(config.getUserName(),config.getPassword())
                .execute().body();
        log.info("post res:{}",res);
        return res.equals("{\"code\":0}");
    }
}
